package controllers

import (
	"encoding/json"
	"fmt"
	"github.com/astaxie/beego/cache"
	"github.com/astaxie/beego/orm"
	"goweb/models"
	"time"
)

type HomeController struct {
	CommonController
}

func (this *HomeController) Getmain() {
	this.Data["Website"] = "beego.me"
	this.Data["Email"] = "astaxie@gmail.com"
	this.TplName = "main/main.html"
}

func (this *HomeController) Index() {
	this.TplName = "index/index.html"
}

func (this *HomeController) Area() {
	//冲缓存重获取
	redis_cnn, err := cache.NewCache("redis", `{"key":"goweb","conn":"127.0.0.1:6379","dbNum":"1"}`)
	areainfo := redis_cnn.Get("areas")

	if areainfo != nil {
		list := make(map[string]interface{})
		json.Unmarshal(areainfo.([]byte), &list)
		this.Data["list"] = list
		this.TplName = "area/index.html"
	}

	//从数据库拿数据
	var areas []models.Area
	o := orm.NewOrm()
	num, err := o.QueryTable("area").All(&areas)
	fmt.Println(areas)
	if err != nil {
		fmt.Println("error:", "查询失败")
		return
	}
	if num == 0 {
		fmt.Println("error:", "没有查询到相关数据")
		return
	}

	//把数据写入redis
	json_str, err := json.Marshal(areas)
	if err != nil {
		fmt.Println("encoding err")
		return
	}
	fmt.Println("json_str=", json_str)
	errinfo := redis_cnn.Put("areas", json_str, time.Second*60)
	if errinfo != nil {
		fmt.Println("redis写入错误")
	}
	this.Data["list"] = areas
	this.TplName = "area/index.html"
}

func (this *HomeController) Add() {
	this.TplName = "area/add.html"
}

func (this *HomeController) Addsubmit() {
	resp := make(map[string]interface{})
	resp["errno"] = 1
	defer this.RetData(resp)

	param := make(map[string]interface{})
	json.Unmarshal(this.Ctx.Input.RequestBody, &param)
	o := orm.NewOrm()
	var area models.Area
	area.Name = param["name"].(string)
	_, err := o.Insert(&area)
	if err == nil {
		resp["errmsg"] = "新增成功"
		return
	}
	fmt.Println("err:", err)
	resp["errno"] = 0
	resp["errmsg"] = "新增失败"
}
